package cn.edu.zafu.bigdata.rwx.web;

import javax.imageio.IIOException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {
    private Socket clientSocket;
    private PrintWriter out;
    private BufferedReader in;

    public void startClient(String ip, int port) throws Exception {
        try {
            clientSocket = new Socket(ip, port);
            out = new PrintWriter(clientSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
            String userInput;
            System.out.println("请输入要发送的消息：（输入‘退出’结束）：");
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
                System.out.println("服务器返回的消息：" + in.readLine());
                if (userInput.equals("退出")) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            stopClient();
        }
    }

    public void stopClient() {
        try {
            in.close();
            out.close();
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        String ip = "127.0.0.1";
        int port = 12345;
        Client client = new Client();
        client.startClient(ip, port);
    }
}
